package com.example.campuslink.viewModel.search

import android.content.Intent
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.campuslink.commen.db.school.SchoolInfoTable
import com.example.campuslink.commen.db.search.SearchTable
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.commen.tools.SpKey
import com.example.campuslink.commen.tools.putExtraKey
import com.example.campuslink.model.SearchWordData
import com.example.campuslink.ui.activity.search.SearchResultActivity
import com.example.campuslink.viewModel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class SearchMainViewModel : BaseViewModel() {
    private val _schoolSearch = MutableLiveData<MutableList<SearchWordData>>()
    val schoolSearch get() = _schoolSearch
    private val _schoolInfo = MutableLiveData<SchoolInfoTable>()
    val schoolInfo get() = _schoolInfo
    fun getAllSchoolSearch() {
        viewModelScope?.launch(Dispatchers.IO) {
            val userNumberInfo = userNumberDao?.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: return@launch
            )
            val schoolInfoTable =
                schoolInfoDao?.getSchoolInfoBySchoolName(userNumberInfo?.schoolName ?: "")
            if (schoolInfoTable?.searchData?.size == 0) {
                schoolInfoTable?.searchData = mutableListOf()
                schoolInfoDao?.updateSchoolInfo(schoolInfoTable ?: return@launch)
            }
            _schoolInfo.postValue(schoolInfoTable ?: SchoolInfoTable())
            _schoolSearch.postValue(schoolInfoTable?.searchData)
        }
    }


    fun jumpToSearchResult(searchWord: String) {
        startActivity(Intent().apply {
            putExtra(putExtraKey.SEARCH_WORD.key, searchWord)
        }, targetClass = SearchResultActivity::class.java)
    }

    private val _searchInfo = MutableLiveData<MutableList<SearchWordData>>()
    val searchInfo get() = _searchInfo

    fun deleteSearchInfo(searchContent: String) {
        viewModelScope?.launch(Dispatchers.IO) {
            val userNumberInfo = userNumberDao?.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: return@launch
            )
            val schoolInfoTable =
                schoolInfoDao?.getSchoolInfoBySchoolName(userNumberInfo?.schoolName ?: "")

            val searchTable = searchDao?.getSearchData(userNumberInfo?.telNumber ?: "")
            searchTable?.searchData?.removeAll { it.searchWord == searchContent }
            schoolInfoTable?.searchData?.forEach {
                if (it.searchWord == searchContent) {
                    it.searchCount--
                }
                if (it.searchCount < 0) {
                    schoolInfoTable?.searchData?.remove(it)
                }
            }
            schoolInfoDao?.updateSchoolInfo(schoolInfoTable ?: SchoolInfoTable())
            _schoolSearch.postValue(schoolInfoTable?.searchData)
            searchDao?.updateSearchData(searchTable!!)
            _searchInfo.postValue(searchTable?.searchData)
        }
    }

    fun addSearchInfo(searchContent: String) {
        viewModelScope?.launch(Dispatchers.IO) {
//            var needNotifyData = false
            val userNumberInfo = userNumberDao?.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: return@launch
            )
            val schoolInfoTable =
                schoolInfoDao?.getSchoolInfoBySchoolName(userNumberInfo?.schoolName ?: "")

            val searchTable = searchDao?.getSearchData(userNumberInfo?.telNumber ?: "")
            searchTable?.searchData?.removeAll { it.searchWord == searchContent }
//            schoolInfoTable?.searchData?.forEach {
//                if (searchContent !in it.searchWord) {
//                    schoolInfoTable.searchData.add(SearchWordData().apply {
//                        searchWord = searchContent
//                        searchCount = 1
//                    })
//                    needNotifyData = true
//                }
//                if (it.searchWord == searchContent) {
//                    it.searchCount++
//                    needNotifyData = true
//                }
//            }
            var found = false
            schoolInfoTable?.searchData?.forEach {
                if (it.searchWord == searchContent) {
                    it.searchCount++
                    found = true
                }
            }
            if (!found) {
                schoolInfoTable?.searchData?.add(
                    SearchWordData(
                        searchWord = searchContent,
                        searchCount = 1
                    )
                )
            }

            schoolInfoDao?.updateSchoolInfo(schoolInfoTable ?: SchoolInfoTable())
            _schoolSearch.postValue(schoolInfoTable?.searchData)

            searchTable?.searchData?.add(SearchWordData().apply {
                searchWord = searchContent
            })
            searchDao?.updateSearchData(searchTable!!)
            _searchInfo.postValue(searchTable?.searchData)
        }
    }

    fun getSearchInfo() {

        viewModelScope?.launch(Dispatchers.IO) {
            val userNumberInfo = userNumberDao?.getUserNumber(
                Sp.getString(
                    context ?: return@launch,
                    SpKey.USER_NUMBER.key ?: "",
                    ""
                ) ?: return@launch
            )
            var searchTable = searchDao?.getSearchData(userNumberInfo?.telNumber ?: "")
            if (searchTable == null) {
                searchTable = SearchTable().apply {
                    schoolId = _schoolInfo.value?.id ?: 0
                    UserNumber = userNumberInfo?.telNumber ?: ""
                    searchData = mutableListOf()
                }
                searchDao?.insertSearchData(searchTable)
                searchTable = searchDao?.getSearchData(userNumberInfo?.telNumber ?: "")
            }
            _searchInfo.postValue(searchTable?.searchData)

//            searchTable?.searchData?.forEach {
//                if (it.searchWord == searchContent) {
//                    searchTable?.searchData?.remove(it)
//                }
//            }

        }
    }
}